package org.budo.mongo.jdbc.driver.statement.impl;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.Map;

import org.budo.jdbc.driver.AbstractBudoJdbcPreparedStatement;
import org.budo.jdbc.driver.resultset.impl.IteratorResultSet;
import org.budo.mongo.jdbc.driver.BudoMongoJdbcResultSetMetaData;
import org.budo.mongo.jdbc.driver.executor.MongoStatementExecutor;
import org.budo.mongo.jdbc.driver.statement.AbstractMongoStatement;
import org.budo.mongo.jdbc.driver.statement.StatementDocument;

/**
 * @author li
 */
public class MongoFindStatement extends AbstractMongoStatement {
    public void execute(PreparedStatement preparedStatement) throws SQLException {
        StatementDocument statementDocument = this.statementDocument(preparedStatement);

        MongoStatementExecutor statementExecutor = this.statementExecutor(preparedStatement);

        // 执行查询
        Iterator<?> iterator = statementExecutor.find(this.getCollectionName(), statementDocument);

        @SuppressWarnings("resource")
        IteratorResultSet resultSet = new IteratorResultSet();
        resultSet.setIterator(iterator); // 结果值

        // 无结果
        if (!iterator.hasNext()) {
            resultSet.setMetaData(this.getResultSetMetaData()); // MetaData

            ((AbstractBudoJdbcPreparedStatement) preparedStatement).setResultSet(resultSet);
            return;
        }

        // 先把第一行读出来，得到列信息，然后暂存第一行
        Map<?, ?> next = (Map<?, ?>) iterator.next();
        String[] columnNames = next.keySet().toArray(new String[next.size()]);

        BudoMongoJdbcResultSetMetaData metaData = new BudoMongoJdbcResultSetMetaData(columnNames);
        resultSet.setMetaData(metaData);
        resultSet.setNext(next);
        ((AbstractBudoJdbcPreparedStatement) preparedStatement).setResultSet(resultSet);
    }
}